<!-- 商品发布 - 营销设置 -->
<template>
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="130px" :disabled="isDetail">
    <div
      v-if="formData.salesChannel?.includes(2)"
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>服务承诺</span>
    </div>
    <el-form-item label="商品服务承诺" prop="promiseList" v-if="formData.salesChannel?.includes(2)">
      <div class="w-100% border-rd-5px">
        <el-tag
          effect="dark"
          class="mr-15px"
          size="large"
          closable
          v-for="(item, index) in formData.promiseList"
          :key="item.id"
          @close="formData.promiseList?.splice(index, 1)"
          >{{ item.name }}</el-tag
        >
        <el-button @click="addTag('browseMember')">添加服务承诺</el-button>
      </div>
      <Explaintip
        msg="商品服务标签示例"
        :isPicUrl="true"
        picUrl="https://v5.100cms.com.cn/static/dist/shop/img/shop_tag.png"
      />
    </el-form-item>
    <div
      class="p-10px border-rd-5px mb-20px border-1px bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      积分获取设置
    </div>
    <el-form-item label="会员积分获取" prop="memberIntegral">
      <div class="w-100%">
        <el-radio-group
          v-model="formData.memberIntegral!.selectId"
          @change="onMemberchange('memberIntegral')"
        >
          <el-radio :value="0">不积分</el-radio>
          <el-radio :value="1">系统默认</el-radio>
          <el-radio :value="2">自定义积分</el-radio>
        </el-radio-group>
      </div>
    </el-form-item>
    <template v-if="formData.memberIntegral?.selectId == 2">
      <el-form-item v-if="!formData.specType">
        <SkuListMemberShip
          ref="skuListMembershipRef"
          :prop-form-data="formData"
          :property-list="propertyList"
          :rule-config="memberIntegralRuleConfig"
          :rule-type="'memberIntegral'"
        />
      </el-form-item>
      <template v-if="formData.specType && propertyList.length > 0">
        <el-form-item v-if="!isDetail" label="批量设置">
          <SkuListMemberShip
            :is-batch="true"
            :prop-form-data="formData"
            :property-list="propertyList"
            :rule-type="'memberIntegral'"
          />
        </el-form-item>
        <el-form-item label="规格列表">
          <SkuListMemberShip
            ref="skuListMembershipRef"
            :is-detail="isDetail"
            :prop-form-data="formData"
            :property-list="propertyList"
            :rule-config="memberIntegralRuleConfig"
            :rule-type="'memberIntegral'"
          />
        </el-form-item>
      </template>
    </template>
    <el-form-item label="付费会员积分获取" prop="paidmemberIntegral">
      <div class="w-100%">
        <el-radio-group
          v-model="formData.paidmemberIntegral!.selectId"
          @change="onPaidMemberchange('paidmemberIntegral')"
        >
          <el-radio :value="0">不积分</el-radio>
          <el-radio :value="1">系统默认</el-radio>
          <el-radio :value="2">自定义积分</el-radio>
        </el-radio-group>
      </div>
    </el-form-item>
    <template v-if="formData.paidmemberIntegral?.selectId == 2">
      <el-form-item v-if="!formData.specType">
        <SkuListPaidMemberShip
          ref="skuListPaidMembershipRef"
          :prop-form-data="formData"
          :property-list="propertyList"
          :rule-config="paidmemberIntegralRuleConfig"
          :rule-type="'paidmemberIntegral'"
        />
      </el-form-item>
      <template v-if="formData.specType && propertyList.length > 0">
        <el-form-item v-if="!isDetail" label="批量设置">
          <SkuListPaidMemberShip
            :is-batch="true"
            :prop-form-data="formData"
            :property-list="propertyList"
            :rule-type="'paidmemberIntegral'"
          />
        </el-form-item>
        <el-form-item label="规格列表">
          <SkuListPaidMemberShip
            ref="skuListPaidMembershipRef"
            :is-detail="isDetail"
            :prop-form-data="formData"
            :property-list="propertyList"
            :rule-config="paidmemberIntegralRuleConfig"
            :rule-type="'paidmemberIntegral'"
          />
        </el-form-item>
      </template>
    </template>
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>积分抵扣设置</span>
      <Icon class="ml-5px" :icon="'ep:question-filled'" />
      <span class="ml-5px">
        定义最多抵扣中的【最多抵扣】指一次下单最多可抵扣；【多件累计】指允许多件累计抵扣。
      </span>
    </div>
    <el-form-item label="会员积分抵扣" prop="deduMemberIntegral">
      <div class="w-100%">
        <el-radio-group
          v-model="formData.deduMemberIntegral!.selectId"
          @change="onMemberchange('deduMemberIntegral')"
        >
          <el-radio :value="0">关闭</el-radio>
          <el-radio :value="1">不限制抵扣数量</el-radio>
          <el-radio :value="2">自定义最多抵扣</el-radio>
        </el-radio-group>
      </div>
    </el-form-item>
    <template v-if="formData.deduMemberIntegral?.selectId == 2">
      <el-form-item v-if="!formData.specType">
        <SkuListMemberShip
          ref="skuListMembershipRef"
          :prop-form-data="formData"
          :property-list="propertyList"
          :rule-config="deduMemberIntegralRuleConfig"
          :rule-type="'deduMemberIntegral'"
        />
      </el-form-item>
      <template v-if="formData.specType && propertyList.length > 0">
        <el-form-item v-if="!isDetail" label="批量设置">
          <SkuListMemberShip
            :is-batch="true"
            :prop-form-data="formData"
            :property-list="propertyList"
            :rule-type="'deduMemberIntegral'"
          />
        </el-form-item>
        <el-form-item label="规格列表">
          <SkuListMemberShip
            ref="skuListMembershipRef"
            :is-detail="isDetail"
            :prop-form-data="formData"
            :property-list="propertyList"
            :rule-config="deduMemberIntegralRuleConfig"
            :rule-type="'deduMemberIntegral'"
          />
        </el-form-item>
      </template>
    </template>

    <el-form-item label="付费会员积分抵扣" prop="deduPaidmemberIntegral">
      <div class="w-100%">
        <el-radio-group
          v-model="formData.deduPaidmemberIntegral!.selectId"
          @change="onPaidMemberchange('deduPaidmemberIntegral')"
        >
          <el-radio :value="0">关闭</el-radio>
          <el-radio :value="1">不限制抵扣数量</el-radio>
          <el-radio :value="2">自定义最多抵扣</el-radio>
        </el-radio-group>
      </div>
    </el-form-item>

    <template v-if="formData.deduPaidmemberIntegral?.selectId == 2">
      <el-form-item v-if="!formData.specType">
        <SkuListPaidMemberShip
          ref="skuListPaidMembershipRef"
          :prop-form-data="formData"
          :property-list="propertyList"
          :rule-config="deduPaidmemberIntegralRuleConfig"
          :rule-type="'deduPaidmemberIntegral'"
        />
      </el-form-item>
      <template v-if="formData.specType && propertyList.length > 0">
        <el-form-item v-if="!isDetail" label="批量设置">
          <SkuListPaidMemberShip
            :is-batch="true"
            :prop-form-data="formData"
            :property-list="propertyList"
            :rule-type="'deduPaidmemberIntegral'"
          />
        </el-form-item>
        <el-form-item label="规格列表">
          <SkuListPaidMemberShip
            ref="skuListPaidMembershipRef"
            :is-detail="isDetail"
            :prop-form-data="formData"
            :property-list="propertyList"
            :rule-config="deduPaidmemberIntegralRuleConfig"
            :rule-type="'deduPaidmemberIntegral'"
          />
        </el-form-item>
      </template>
    </template>
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>余额抵扣设置</span>
      <Icon class="ml-5px" :icon="'ep:question-filled'" />
      <span class="ml-5px">
        定义最多抵扣中的【最多抵扣】指一次下单最多可抵扣；【多件累计】指允许多件累计抵扣。
      </span>
    </div>
    <el-form-item
      label="会员余额抵扣"
      prop="memberBalance"
      @change="onMemberchange('memberBalance')"
    >
      <div class="w-100%">
        <el-radio-group v-model="formData.memberBalance!.selectId">
          <el-radio :value="0">关闭</el-radio>
          <el-radio :value="1">不限制抵扣数量</el-radio>
          <el-radio :value="2">自定义最多抵扣</el-radio>
        </el-radio-group>
      </div>
    </el-form-item>
    <template v-if="formData.memberBalance?.selectId == 2">
      <el-form-item v-if="!formData.specType">
        <SkuListMemberShip
          ref="skuListMembershipRef"
          :prop-form-data="formData"
          :property-list="propertyList"
          :rule-config="memberBalanceRuleConfig"
          :rule-type="'memberBalance'"
        />
      </el-form-item>
      <template v-if="formData.specType && propertyList.length > 0">
        <el-form-item v-if="!isDetail" label="批量设置">
          <SkuListMemberShip
            :is-batch="true"
            :prop-form-data="formData"
            :property-list="propertyList"
            :rule-type="'memberBalance'"
          />
        </el-form-item>
        <el-form-item label="规格列表">
          <SkuListMemberShip
            ref="skuListMembershipRef"
            :is-detail="isDetail"
            :prop-form-data="formData"
            :property-list="propertyList"
            :rule-config="memberBalanceRuleConfig"
            :rule-type="'memberBalance'"
          />
        </el-form-item>
      </template>
    </template>

    <el-form-item label="付费会员余额抵扣" prop="paidmemberBalance">
      <div class="w-100%">
        <el-radio-group
          v-model="formData.paidmemberBalance!.selectId"
          @change="onPaidMemberchange('paidmemberBalance')"
        >
          <el-radio :value="0">关闭</el-radio>
          <el-radio :value="1">不限制抵扣数量</el-radio>
          <el-radio :value="2">自定义最多抵扣</el-radio>
        </el-radio-group>
      </div>
    </el-form-item>

    <template v-if="formData.paidmemberBalance?.selectId == 2">
      <el-form-item v-if="!formData.specType">
        <SkuListPaidMemberShip
          ref="skuListPaidMembershipRef"
          :prop-form-data="formData"
          :property-list="propertyList"
          :rule-config="paidmemberBalanceRuleConfig"
          :rule-type="'paidmemberBalance'"
        />
      </el-form-item>
      <template v-if="formData.specType && propertyList.length > 0">
        <el-form-item v-if="!isDetail" label="批量设置">
          <SkuListPaidMemberShip
            :is-batch="true"
            :prop-form-data="formData"
            :property-list="propertyList"
            :rule-type="'paidmemberBalance'"
          />
        </el-form-item>
        <el-form-item label="规格列表">
          <SkuListPaidMemberShip
            ref="skuListPaidMembershipRef"
            :is-detail="isDetail"
            :prop-form-data="formData"
            :property-list="propertyList"
            :rule-config="paidmemberBalanceRuleConfig"
            :rule-type="'paidmemberBalance'"
          />
        </el-form-item>
      </template>
    </template>

    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>关联代金券设置</span>
      <Icon class="ml-5px" :icon="'ep:question-filled'" />
      <span class="ml-5px"> 关联代金券设置 </span>
    </div>
    <el-form-item label="代金券设置" prop="voucherSelectId">
      <div class="w-100%">
        <el-radio-group v-model="formData.voucherSelectId" @change="onCouponchange()">
          <el-radio :value="0">不参与</el-radio>
          <el-radio :value="1">统一设置</el-radio>
          <el-radio :value="2">单一设置</el-radio>
        </el-radio-group>
      </div>
    </el-form-item>
    <template v-if="formData.voucherSelectId == 1">
      <el-form-item>
        <div class="w-100%">
          <el-button @click="handleAddCoupon()">添加代金券</el-button>
          <CouponList v-model:multiple-selection="couponList" :is-detail="isDetail" class="mt-20px">
            <template #extension>
              <el-table-column align="center" label="关联数量" prop="number" min-width="168">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.number"
                    :disabled="isDetail"
                    :min="0"
                    :precision="0"
                    :step="1"
                    class="w-120px!"
                    controls-position="right"
                  />
                </template>
              </el-table-column>
            </template>
          </CouponList>
        </div>
      </el-form-item>
    </template>
    <template v-if="formData.voucherSelectId == 2">
      <el-form-item>
        <div class="w-100%">
          <!-- 会员优惠券 -->
          <el-form-item v-if="!formData.specType">
            <SkuListMemberShip
              ref="skuListMembershipRef"
              :prop-form-data="formData"
              :property-list="propertyList"
              :rule-config="ruleConfig"
              :rule-type="'coupon'"
            />
          </el-form-item>
          <template v-if="formData.specType && propertyList.length > 0">
            <el-form-item v-if="!isDetail" label="批量设置">
              <SkuListMemberShip
                :is-batch="true"
                :prop-form-data="formData"
                :property-list="propertyList"
                :rule-type="'coupon'"
              />
            </el-form-item>
            <el-form-item label="规格列表">
              <SkuListMemberShip
                ref="skuListMembershipRef"
                :is-detail="isDetail"
                :prop-form-data="formData"
                :property-list="propertyList"
                :rule-config="ruleConfig"
                :rule-type="'coupon'"
              />
            </el-form-item>
          </template>
          <!-- 付费会员优惠券 -->
          <div class="mt-20px">
            <el-form-item v-if="!formData.specType">
              <SkuListPaidMemberShip
                ref="skuListPaidMembershipRef"
                :prop-form-data="formData"
                :property-list="propertyList"
                :rule-config="ruleConfig"
                :rule-type="'paycoupon'"
              />
            </el-form-item>
            <template v-if="formData.specType && propertyList.length > 0">
              <el-form-item v-if="!isDetail" label="批量设置">
                <SkuListPaidMemberShip
                  :is-batch="true"
                  :prop-form-data="formData"
                  :property-list="propertyList"
                  :rule-type="'paycoupon'"
                />
              </el-form-item>
              <el-form-item label="规格列表">
                <SkuListPaidMemberShip
                  ref="skuListPaidMembershipRef"
                  :is-detail="isDetail"
                  :prop-form-data="formData"
                  :property-list="propertyList"
                  :rule-config="ruleConfig"
                  :rule-type="'paycoupon'"
                />
              </el-form-item>
            </template>
          </div>
        </div>
      </el-form-item>
    </template>
  </el-form>

  <CouponSelect
    ref="couponSelectDialog"
    v-model:multiple-selection="couponList"
    :take-type="CouponTemplateTakeTypeEnum.ADMIN.type"
  >
    <template #extension>
      <el-table-column align="center" label="关联数量" prop="number" min-width="168">
        <template #default="{ row }">
          <el-input-number
            v-model="row.number"
            :min="0"
            :precision="0"
            :step="1"
            class="w-120px!"
            controls-position="right"
          />
        </template>
      </el-table-column>
    </template>
  </CouponSelect>
</template>
<script lang="ts" setup>
import type { Spu } from '@/api/mall/product/spu'
import { PropType } from 'vue'
import { propTypes } from '@/utils/propTypes'
import { copyValueToTarget } from '@/utils'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import {
  getPropertyList,
  PropertyAndValues,
  RuleConfig,
  SkuListMemberShip,
  SkuListPaidMemberShip,
  CouponList
} from '@/views/mall/product/spu/components/index'
defineOptions({ name: 'ProductPromotionForm' })
/**优惠券功能 */
// 优惠券列表
import CouponSelect from '@/views/mall/promotion/coupon/components/CouponSelect.vue'
import * as CouponTemplateApi from '@/api/mall/promotion/coupon/couponTemplate'
import { CouponTemplateTakeTypeEnum } from '@/utils/constants'

const couponList = ref<CouponTemplateApi.CouponTemplateVO[]>([])
const couponSelectDialog = ref()
// 添加优惠券
const handleAddCoupon = () => {
  couponSelectDialog.value.open()
}
const memberIntegralRuleConfig: RuleConfig[] = []
const deduMemberIntegralRuleConfig: RuleConfig[] = []
const memberBalanceRuleConfig: RuleConfig[] = []
const memberDiscountRuleConfig: RuleConfig[] = []
const paidmemberIntegralRuleConfig: RuleConfig[] = []
const deduPaidmemberIntegralRuleConfig: RuleConfig[] = []
const paidmemberBalanceRuleConfig: RuleConfig[] = []
const paidmemberDiscountRuleConfig: RuleConfig[] = []
let membershipLevelType = getIntDictOptions(DICT_TYPE.METON_MEMBERSHIP_LEVEL)
let paidMembershipLevelType = getIntDictOptions(DICT_TYPE.METON_PAID_MEMBERSHIP_LEVEL)

membershipLevelType.forEach((ele) => {
  memberIntegralRuleConfig.push({
    name: `memberIntegral${ele.value}`,
    rule: (arg) => arg >= 0,
    message: ''
  })
  deduMemberIntegralRuleConfig.push({
    name: `deduMemberIntegral${ele.value}`,
    rule: (arg) => arg >= 0 && arg != '',
    message: ''
  })
  memberBalanceRuleConfig.push({
    name: `memberBalance${ele.value}`,
    rule: (arg) => arg >= 0 && arg != '',
    message: ''
  })
  memberDiscountRuleConfig.push({
    name: `memberDiscount${ele.value}`,
    rule: (arg) => arg >= 0 && arg != '',
    message: ''
  })
})
paidMembershipLevelType.forEach((ele) => {
  paidmemberIntegralRuleConfig.push({
    name: `paidmemberIntegral${ele.value}`,
    rule: (arg) => arg >= 0 && arg != '',
    message: ''
  })
  deduPaidmemberIntegralRuleConfig.push({
    name: `deduPaidmemberIntegral${ele.value}`,
    rule: (arg) => arg >= 0 && arg != '',
    message: ''
  })
  paidmemberBalanceRuleConfig.push({
    name: `paidmemberBalance${ele.value}`,
    rule: (arg) => arg >= 0 && arg != '',
    message: ''
  })
  paidmemberDiscountRuleConfig.push({
    name: `paidmemberDiscount${ele.value}`,
    rule: (arg) => arg >= 0 && arg != '',
    message: ''
  })
})
const message = useMessage() // 消息弹窗

const props = defineProps({
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => {}
  },
  activeName: propTypes.string.def(''),
  isDetail: propTypes.bool.def(false) // 是否作为详情组件
})

const formRef = ref() // 表单Ref
const propertyList = ref<PropertyAndValues[]>([]) // 商品属性列表
const skuListMembershipRef = ref() // 商品属性列表 Ref
const skuListPaidMembershipRef = ref()
// 表单数据
const formData = ref<Spu>({
  specType: false, // 商品规格
  skus: [],
  promiseList: [], //服务承诺
  salesChannel: [], //销售渠道

  memberIntegral: {
    selectId: 0,
    ruleList: []
  }, //会员积分设置
  paidmemberIntegral: {
    selectId: 0,
    ruleList: []
  }, //付费会员积分设置
  deduMemberIntegral: {
    selectId: 0,
    ruleList: []
  },
  deduPaidmemberIntegral: {
    selectId: 0,
    ruleList: []
  },
  memberBalance: {
    selectId: 0,
    ruleList: []
  },
  paidmemberBalance: {
    selectId: 0,
    ruleList: []
  },
  voucherSelectId: 0
})
// 表单规则
const rules = reactive({})
/**会员选择改变 */
const onMemberchange = (type: any) => {
  formData.value.skus?.forEach((element) => {
    membershipLevelType.forEach((ele) => {
      element[`${type}${ele.value}`] = undefined
      element[`${type}${ele.value}ruleType`] = 0
    })
  })
}
const onPaidMemberchange = (type: any) => {
  formData.value.skus?.forEach((element) => {
    paidMembershipLevelType.forEach((ele) => {
      element[`${type}${ele.value}`] = undefined
      element[`${type}${ele.value}ruleType`] = 0
    })
  })
}
const onCouponchange = () => {
  couponList.value = []
  onMemberchange('coupon')
  onPaidMemberchange('paycoupon')
}

/**付费会员选择改变 */

/** 将传进来的值赋值给 formData */
watch(
  () => props.propFormData,
  (data) => {
    if (!data) {
      return
    }
    copyValueToTarget(formData.value, data)
    // 将 SKU 的属性，整理成 PropertyAndValues 数组
    propertyList.value = getPropertyList(data)
  },
  {
    deep: true,
    immediate: true
  }
)

/** 表单校验 */
const emit = defineEmits(['update:activeName'])
const validate = async () => {
  if (!formRef) return
  try {
    skuListMembershipRef.value?.validateSku()
    skuListPaidMembershipRef.value?.validateSku()

    await unref(formRef)?.validate()
    // 会员 积分获取 抵扣 余额抵扣
    formData.value.memberIntegral!.ruleList = []
    formData.value.deduMemberIntegral!.ruleList = []
    formData.value.memberBalance!.ruleList = []
    // 付费会员 积分获取 抵扣 余额抵扣

    formData.value.paidmemberIntegral!.ruleList = []
    formData.value.deduPaidmemberIntegral!.ruleList = []
    formData.value.paidmemberBalance!.ruleList = []
    formData.value.skus?.forEach((ele) => {
      //会员积分获取
      if (formData.value.memberIntegral?.selectId == 2) {
        formData.value.memberIntegral!.ruleList?.push({
          skuSpecList: ele.properties,
          memberList: membershipLevelType.map((item) => {
            return {
              shipLevel: item.value,
              ruleValue: ele[`memberIntegral${item.value}`],
              ruleType: ele[`memberIntegral${item.value}ruleType`]
            }
          })
        })
      }

      // 会员积分抵扣
      formData.value.deduMemberIntegral!.ruleList?.push({
        skuSpecList: ele.properties,
        memberList: membershipLevelType.map((item) => {
          return {
            shipLevel: item.value,
            ruleValue: ele[`deduMemberIntegral${item.value}`],
            ruleType: ele[`deduMemberIntegral${item.value}ruleType`]
          }
        })
      })
      // 会员余额抵扣
      formData.value.memberBalance!.ruleList?.push({
        skuSpecList: ele.properties,
        memberList: membershipLevelType.map((item) => {
          return {
            shipLevel: item.value,
            ruleValue: ele[`memberBalance${item.value}`],
            ruleType: ele[`memberBalance${item.value}ruleType`]
          }
        })
      })
      // 付费会员积分获取
      formData.value.paidmemberIntegral!.ruleList?.push({
        skuSpecList: ele.properties,
        memberList: paidMembershipLevelType.map((item) => {
          return {
            shipLevel: item.value,
            ruleValue: ele[`paidmemberIntegral${item.value}`],
            ruleType: ele[`paidmemberIntegral${item.value}ruleType`]
          }
        })
      })
      // 付费会员积分抵扣
      formData.value.deduPaidmemberIntegral!.ruleList?.push({
        skuSpecList: ele.properties,
        memberList: paidMembershipLevelType.map((item) => {
          return {
            shipLevel: item.value,
            ruleValue: ele[`deduPaidmemberIntegral${item.value}`],
            ruleType: ele[`deduPaidmemberIntegral${item.value}ruleType`]
          }
        })
      })
      // 付费会员余额抵扣
      formData.value.paidmemberBalance!.ruleList?.push({
        skuSpecList: ele.properties,
        memberList: paidMembershipLevelType.map((item) => {
          return {
            shipLevel: item.value,
            ruleValue: ele[`paidmemberBalance${item.value}`],
            ruleType: ele[`paidmemberBalance${item.value}ruleType`]
          }
        })
      })
    })
    // 校验通过更新数据
    Object.assign(props.propFormData, formData.value)
  } catch (e) {
    message.error('【营销设置】不完善，请填写相关信息')
    emit('update:activeName', 'promotion')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate })
</script>
